const app = getApp()
const http = require('../../utils/request.js')
const config = require('../../config/' + app.globalData.WX_ENV + '_config.js')
const time = 60 // 发送手机号码时间间隔
let sendVCodeTimer = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    loadingIconPath: '/images/loading.gif',
    loadingText: '正在获取微信安全密钥',
    loginMethod: 'wechat',
    mobile: null,
    captchaDisabled: false,
    captchaDisabledTime: time,
    sessionToken: null,
    redirectUrl: null,
    hasPassLogin: false,
    shopLogoPath: null,
    imageHost: config.IMG_HOST,
  },
  changeMobile() {
    this.setData({
      mobile: null
    })
  },
  // 通过微信加密信息获取手机号
  bindgetphonenumber(e) {
    const that = this
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      http._get('/User/Account/GetMobile', {
        mobileString: e.detail.encryptedData,
        iv: e.detail.iv,
        sessionToken: that.data.sessionToken
      }).then(res => {
        if (res.Code === 100000) {
          wx.showModal({
            title: '提示',
            content: `是否用${res.Data.substr(0, 3)}****${res.Data.substr(7, 4)}作为登录账号`,
            confirmText: '是',
            cancelText: '其他号码',
            success(result) {
              if (result.confirm) {
                that.setData({
                  mobile: res.Data
                })
                that.loginByMobile({
                  mobileToken: that.data.sessionToken
                })
              } else if (result.cancel) {
                that.setData({
                  mobile: '',
                  loginMethod: 'mobile'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: res.Msg,
            icon: 'none',
            duration: 1500
          })
        }
      })
    }
  },
  /**
   * 更换登陆方式
   */
  changeLoginMethod(e) {
    this.setData({
      mobile: '',
      loginMethod: e.currentTarget.dataset.loginmethod
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this
    let redirectUrl = options.redirectUrl
    if (redirectUrl) {
      this.setData({
        redirectUrl: "/" + decodeURIComponent(options.redirectUrl)
      })
    } else {
      this.setData({
        redirectUrl: "/pages/index/index"
      })
    }
    wx.login({
      success(res) {
        that.getSessionKey(res.code).then(data => {
          that.setData({
            loading: false,
            sessionToken: data
          })
        }).catch(e => {
          that.setData({
            loadingIconPath: '/images/api_loading_error.png',
            loadingText: e.message
          })
        })
      }
    })
  },
  /**
   * 点击发送手机验证码按钮
   */
  clickSendMobileBtn(e) {
    let mobile = e.detail.value.mobile
    this.checkMobileThenSend(mobile)
  },
  /**
   * 点击键盘上的发送按钮
   */
  mobileInputBindconfirm(e) {
    let mobile = e.detail.value
    this.checkMobileThenSend(mobile)
  },
  /**
   * 点击重发验证码按钮
   */
  clickReSendMobileVCodeBtn() {
    this.checkMobileThenSend(this.data.mobile)
  },
  /**
   * 验证手机号码然后发送
   */
  checkMobileThenSend(mobile) {
    if (!mobile.trim()) {
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none',
        duration: 1500
      })
      return false
    }
    var mobileReg = /^((13|14|15|17|18)[0-9]{1}\d{8})$/
    if (!mobileReg.test(mobile)) {
      wx.showToast({
        title: '手机号码格式错误',
        icon: 'none',
        duration: 1500
      })
      return false
    }
    this.sendMobileVCode(mobile)
  },
  /**
   * 发送手机验证码
   */
  sendMobileVCode(mobile) {
    this.setData({
      captchaDisabled: true,
      captchaDisabledTime: time
    })
    http._get('/ResourceLibrary/SendVCode', {
      mobile: mobile
    }, {
        loadingText: '正在发送…'
      }).then(res => {
        if (res.Code === 100000) {
          this.setData({
            mobile: mobile
          })
          this.setCaptchaTime()
        } else {
          wx.showToast({
            title: res.Msg,
            icon: 'none',
            duration: 1500
          })
          clearTimeout(sendVCodeTimer)
          this.setData({
            captchaDisabled: false
          })
        }
      })
  },
  // 发送验证码倒计时
  setCaptchaTime() {
    const that = this
    if (that.data.captchaDisabledTime > 0) {
      let remainingTime = that.data.captchaDisabledTime - 1
      that.setData({
        captchaDisabledTime: remainingTime
      })
      sendVCodeTimer = setTimeout(function () {
        that.setCaptchaTime()
      }, 1000)
    } else {
      clearTimeout(sendVCodeTimer)
      this.setData({
        captchaDisabled: false
      })
    }
  },
  /**
   * 表单提交验证码
   */
  submitFormToLogin(e) {
    let vCode = e.detail.value.vCode
    this.checkVCodeThenSubmit(vCode)
  },
  /**
   * 键盘按钮提交验证码
   */
  vcodeInputBindconfirm(e) {
    let vCode = e.detail.value
    this.checkVCodeThenSubmit(vCode)
  },
  checkVCodeThenSubmit(vCode) {
    if (!vCode.trim()) {
      wx.showToast({
        title: '验证码不能为空',
        icon: 'none',
        duration: 1500
      })
      return false
    }
    this.loginByMobile({
      vCode: vCode
    })
  },
  /**
   * 通过手机号码登陆
   */
  loginByMobile({ vCode = '', mobileToken = '' }) {
    http._post(`/User/Account/LoginMobile?mobile=${this.data.mobile}&mobileToken=${mobileToken}`, {
    }, {
      loadingText: '登录中'
    }).then(res => {
      this.loginSuccess(res)
    })
  },
  /**
   * 获取SessionKey
   */
  getSessionKey(code) {
    return new Promise((resolve, reject) => {
      http._get('/User/Account/GetSessionKey', {
        code: code
      }, {
          loading: false
        }).then(res => {
          if (res.Code === 100000) {
            resolve(res.Data)
          } else {
            reject(new Error(res.Msg))
          }
        }).catch(error => {
          reject(new Error('服务器繁忙，请稍后重试！'))
        })
    })
  },
  /**
   * 登陆成功
   */
  loginSuccess(res) {
    if (res.Code === 100000) {
      wx.setStorageSync('Token', res.Data.Token)
      this.getUserinfo().then(res => {
        if (res.Code === 100000) {
          wx.setStorageSync('userInfo', res.Data)
        }
        const tabBars = ['/pages/index/index', '/pages/photoGallery/index/index', '/pages/mine/index']
        if (tabBars.indexOf(this.data.redirectUrl) >= 0) {
          wx.switchTab({
            url: this.data.redirectUrl,
          })
        } else {
          wx.redirectTo({
            url: this.data.redirectUrl,
          })
        }
      })
    } else {
      app.globalData.Token = ''
      wx.showToast({
        title: res.Msg,
        icon: 'none',
        duration: 1500
      })
    }
  },
  /**
   * 获取用户信息
   */
  getUserinfo () {
    return new Promise(resolve => {
      http._get('/User/Account/Info', {
      }, {
        loadingText: '获取用户信息'
      }).then(res => {
        resolve(res)
      }).catch(error => {
        this.setData({
          loadingIconPath: '/images/api_loading_error.png',
          loadingText: '服务器繁忙，请稍后重试！'
        })
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  }
})